import React, { useState, useEffect } from 'react';
import { 
  Table, Input, Button, Space, Modal, Form, 
  Upload, InputNumber, Select, DatePicker, 
  message, Popconfirm, Tag, Tooltip, Badge,
  Card, Statistic, Row, Col, Progress,  
} from 'antd';
import { 
  CaretRightOutlined, UploadOutlined, 
  ExclamationCircleOutlined, PlusOutlined,
  FileExcelOutlined, ImportOutlined,
  PrinterOutlined, BarChartOutlined,
  ReloadOutlined, DownloadOutlined
} from '@ant-design/icons';
import type { UploadFile } from 'antd/es/upload/interface';
// import type { RangePickerProps } from 'antd/es/date-picker';
// import moment from 'moment';
import type { ColumnsType } from 'antd/es/table'; 
import './emergencyStock.less';

// 主表格数据接口
interface MainTableItem {
  key: string;
  sequence: number;
  itemName: string;
  unit: string;
  totalQuantity: number;
  usedQuantity: number;
  image: string;
  totalValue: number;
  category: string;
  status: 'normal' | 'warning' | 'danger';
  lastUpdateTime: string;
  location: string;
}

// 详情表格数据接口
interface DetailTableItem {
  key: string;
  sequence: number;
  modelNumber: string;
  price: number;
  quantity: number;
  totalPrice: number;
  date: string;
  supplier: string;
  batchNumber: string;
  expiryDate: string;
  remark: string;
}

// 统计数据接口
interface StockStatistics {
  totalItems: number;
  totalValue: number;
  lowStockItems: number;
  expiringItems: number;
}

const EmergencyStock: React.FC = () => {
  // 状态管理
  const [expandedRowKeys, setExpandedRowKeys] = useState<string[]>([]);
  const [addModalVisible, setAddModalVisible] = useState(false);
  const [imageModalVisible, setImageModalVisible] = useState(false);
  const [statsModalVisible, setStatsModalVisible] = useState(false);
  const [currentImage, setCurrentImage] = useState('');
  const [loading, setLoading] = useState(false);
  const [form] = Form.useForm();
  const [fileList, setFileList] = useState<UploadFile[]>([]);
  const [selectedRows, setSelectedRows] = useState<MainTableItem[]>([]);
  const [importModalVisible, setImportModalVisible] = useState(false);
  const [searchParams, setSearchParams] = useState({
    keyword: '',
    status: undefined,
    category: undefined,
    dateRange: undefined,
  });
  const [statistics, setStatistics] = useState<StockStatistics>({
    totalItems: 0,
    totalValue: 0,
    lowStockItems: 0,
    expiringItems: 0,
  });

  // 初始化加载
  useEffect(() => {
    fetchData();
    fetchStatistics();
  }, [searchParams]);

  // 获取数据
  const fetchData = async () => {
    try {
      setLoading(true);
      // 模拟API调用
      await new Promise(resolve => setTimeout(resolve, 1000));
      // 实际项目中这里应该调用后端API
      setLoading(false);
    } catch (error) {
      message.error('数据加载失败');
      setLoading(false);
    }
  };

  // 获取统计数据
  const fetchStatistics = async () => {
    try {
      // 模拟API调用
      await new Promise(resolve => setTimeout(resolve, 500));
      setStatistics({
        totalItems: 156,
        totalValue: 52800,
        lowStockItems: 8,
        expiringItems: 3,
      });
    } catch (error) {
      message.error('统计数据加载失败');
    }
  };

  // 处理搜索
  const handleSearch = (values: any) => {
    setSearchParams(prev => ({
      ...prev,
      ...values,
    }));
  };

  // 处理重置
  const handleReset = () => {
    setSearchParams({
      keyword: '',
      status: undefined,
      category: undefined,
      dateRange: undefined,
    });
    form.resetFields();
  };

  // 渲染统计卡片
  const renderStatistics = () => (
    <Row gutter={16} className='statisticsRow'>
      <Col span={6}>
        <Card>
          <Statistic
            title="物资总数"
            value={statistics.totalItems}
            suffix="件"
          />
        </Card>
      </Col>
      <Col span={6}>
        <Card>
          <Statistic
            title="库存总值"
            value={statistics.totalValue}
            prefix="¥"
            precision={2}
          />
        </Card>
      </Col>
      <Col span={6}>
        <Card>
          <Statistic
            title="库存预警"
            value={statistics.lowStockItems}
            suffix="件"
            valueStyle={{ color: '#ff4d4f' }}
          />
        </Card>
      </Col>
      <Col span={6}>
        <Card>
          <Statistic
            title="即将过期"
            value={statistics.expiringItems}
            suffix="件"
            valueStyle={{ color: '#faad14' }}
          />
        </Card>
      </Col>
    </Row>
  );

  // 渲染搜索栏
  const renderSearchBar = () => (
    <div className='searchBar'>
      <Space wrap>
        <Input.Search
          placeholder="请输入物资名称/编号搜索"
          style={{ width: 250 }}
          onSearch={value => handleSearch({ keyword: value })}
          allowClear
        />
        <Select 
          placeholder="物资状态" 
          style={{ width: 120 }}
          allowClear
          onChange={value => handleSearch({ status: value })}
        >
          <Select.Option value="normal">库存充足</Select.Option>
          <Select.Option value="warning">库存偏低</Select.Option>
          <Select.Option value="danger">库存紧张</Select.Option>
        </Select>
        <Select
          placeholder="物资分类"
          style={{ width: 120 }}
          allowClear
          onChange={value => handleSearch({ category: value })}
        >
          <Select.Option value="equipment">设备器材</Select.Option>
          <Select.Option value="materials">耗材物料</Select.Option>
          <Select.Option value="tools">工具仪器</Select.Option>
        </Select>
        <DatePicker.RangePicker
          style={{ width: 250 }}
          onChange={dates => handleSearch({ dateRange: dates })}
        />
        <Button icon={<ReloadOutlined />} onClick={handleReset}>重置</Button>
      </Space>
      <Space>
        <Button 
          icon={<BarChartOutlined />}
          onClick={() => setStatsModalVisible(true)}
        >
          统计分析
        </Button>
        <Button 
          icon={<DownloadOutlined />}
          onClick={handleDownloadTemplate}
        >
          下载模板
        </Button>
        <Button 
          icon={<ImportOutlined />}
          onClick={() => setImportModalVisible(true)}
        >
          批量导入
        </Button>
        <Button 
          type="primary" 
          icon={<FileExcelOutlined />}
          onClick={handleExport}
          disabled={selectedRows.length === 0}
        >
          导出
        </Button>
        <Button 
          type="primary" 
          icon={<PlusOutlined />}
          onClick={() => setAddModalVisible(true)}
        >
          新增物资
        </Button>
      </Space>
    </div>
  );

  const mainColumns = [
    {
      title: '序号',
      dataIndex: 'sequence',
      width: 80,
    },
    {
      title: '物资名称',
      dataIndex: 'itemName',
      width: 200,
    },
    {
      title: '物资单位',
      dataIndex: 'unit',
      width: 100,
    },
    {
      title: '当前库存数',
      dataIndex: 'totalQuantity',
      width: 120,
      render: (quantity: number) => (
        <Space>
          <Badge status={getStockWarningStatus(quantity)} />
          <Tooltip title={
            quantity <= 5 ? '库存紧张' : 
            quantity <= 10 ? '库存偏低' : '库存充足'
          }>
            {quantity}
          </Tooltip>
        </Space>
      ),
    },
    {
      title: '入库次数',
      dataIndex: 'usedQuantity',
      width: 120,
    },
    {
      title: '照片',
      dataIndex: 'image',
      width: 100,
      render: () => <a style={{ color: '#4169E1' }}>查看</a>,
    },
    {
      title: '价格总金额（元）',
      dataIndex: 'totalValue',
      width: 150,
    },
    {
      title: '操作',
      width: 150,
      render: () => (
        <Space>
          <a style={{ color: '#4169E1' }}>查看</a>
          <span style={{ color: '#999' }}>|</span>
          <a style={{ color: '#FF0000' }}>删除</a>
        </Space>
      ),
    },
  ];

  const detailColumns: ColumnsType<DetailTableItem> = [
    {
      title: '入库批次',
      dataIndex: 'sequence',
      width: 100,
    },
    {
      title: '品牌型号',
      dataIndex: 'modelNumber',
      width: 200,
    },
    {
      title: '单价（元）',
      dataIndex: 'price',
      width: 120,
    },
    {
      title: '剩余数量',
      dataIndex: 'quantity',
      width: 120,
    },
    {
      title: '金额（元）',
      dataIndex: 'totalPrice',
      width: 120,
    },
    {
      title: '质保期限',
      dataIndex: 'date',
      width: 120,
    },
    {
      title: '操作',
      width: 100,
      render: () => <a style={{ color: '#4169E1' }}>查看</a>,
    },
  ];

  const mainData: MainTableItem[] = [
    {
      key: '1',
      sequence: 1,
      itemName: '220V指示灯（绿）',
      unit: '个',
      totalQuantity: 2,
      usedQuantity: 2,
      image: '',
      totalValue: 100.00,
      category: 'equipment',
      status: 'normal',
      lastUpdateTime: '2022-05-01',
      location: '仓库A',
    },
    {
      key: '2',
      sequence: 2,
      itemName: '220V指示灯（黄）',
      unit: '个',
      totalQuantity: 3,
      usedQuantity: 4,
      image: '',
      totalValue: 200.00,
      category: 'equipment',
      status: 'warning',
      lastUpdateTime: '2022-05-01',
      location: '仓库B',
    },
    {
      key: '3',
      sequence: 3,
      itemName: '半导体回路',
      unit: '只',
      totalQuantity: 4,
      usedQuantity: 2,
      image: '',
      totalValue: 200.00,
      category: 'equipment',
      status: 'normal',
      lastUpdateTime: '2022-05-01',
      location: '仓库C',
    },
    {
      key: '4',
      sequence: 4,
      itemName: '电磁阀DFD-20J',
      unit: '个',
      totalQuantity: 5,
      usedQuantity: 2,
      image: '',
      totalValue: 200.00,
      category: 'equipment',
      status: 'danger',
      lastUpdateTime: '2022-05-01',
      location: '仓库D',
    },
  ];

  const detailData: DetailTableItem[] = [
    {
      key: '1',
      sequence: 1,
      modelNumber: 'DC-B-28552',
      price: 20.00,
      quantity: 4,
      totalPrice: 100.00,
      date: '2022-05-01',
      supplier: '供应商A',
      batchNumber: 'B28552',
      expiryDate: '2024-05-01',
      remark: '正常',
    },
    {
      key: '2',
      sequence: 2,
      modelNumber: 'DC-B-10000',
      price: 20.00,
      quantity: 1,
      totalPrice: 100.00,
      date: '2022-05-01',
      supplier: '供应商B',
      batchNumber: 'B10000',
      expiryDate: '2023-05-01',
      remark: '即将过期',
    },
    // ... 更多详情数据
  ];

  // 批量导入模板下载
  const handleDownloadTemplate = () => {
    message.success('模板下载中...');
    // 实际项目中这里应该是一个真实的下载链接
  };

  // 批量导入
  const handleImport = () => {
    setImportModalVisible(true);
  };

  // 批量导出
  const handleExport = () => {
    if (selectedRows.length === 0) {
      message.warning('请选择要导出的物资');
      return;
    }
    message.success(`已选择 ${selectedRows.length} 条记录，开始导出...`);
    // 实际导出逻辑
  };

  // 新增物资
  const handleAdd = () => {
    setAddModalVisible(true);
  };

  // 查看图片
  const handleViewImage = (imageUrl: string) => {
    setCurrentImage(imageUrl);
    setImageModalVisible(true);
  };

  // 删除物资
  const handleDelete = (id: string) => {
    Modal.confirm({
      title: '确认删除',
      icon: <ExclamationCircleOutlined />,
      content: '删除后数据将无法恢复，是否确认删除？',
      onOk() {
        message.success('删除成功');
      },
    });
  };

  // 库存预警
  const getStockWarningStatus = (quantity: number) => {
    if (quantity <= 5) return 'error';
    if (quantity <= 10) return 'warning';
    return 'success';
  };

  // 新增物资表单
  const renderAddModal = () => (
    <Modal
      title="新增物资"
      visible={addModalVisible}
      onCancel={() => {
        setAddModalVisible(false);
        form.resetFields();
      }}
      onOk={() => {
        form.validateFields().then(values => {
          console.log(values);
          message.success('添加成功');
          setAddModalVisible(false);
          form.resetFields();
        });
      }}
      width={600}
    >
      <Form form={form} layout="vertical">
        <Form.Item
          name="itemName"
          label="物资名称"
          rules={[{ required: true, message: '请输入物资名称' }]}
        >
          <Input />
        </Form.Item>
        <Form.Item
          name="unit"
          label="物资单位"
          rules={[{ required: true, message: '请选择物资单位' }]}
        >
          <Select>
            <Select.Option value="个">个</Select.Option>
            <Select.Option value="只">只</Select.Option>
            <Select.Option value="台">台</Select.Option>
          </Select>
        </Form.Item>
        <Form.Item
          name="modelNumber"
          label="品牌型号"
          rules={[{ required: true, message: '请输入品牌型号' }]}
        >
          <Input />
        </Form.Item>
        <Form.Item
          name="price"
          label="单价"
          rules={[{ required: true, message: '请输入单价' }]}
        >
          <InputNumber 
            min={0} 
            precision={2} 
            style={{ width: '100%' }} 
            addonAfter="元"
          />
        </Form.Item>
        <Form.Item
          name="quantity"
          label="数量"
          rules={[{ required: true, message: '请输入数量' }]}
        >
          <InputNumber min={1} style={{ width: '100%' }} />
        </Form.Item>
        <Form.Item
          name="expiryDate"
          label="质保期限"
          rules={[{ required: true, message: '请选择质保期限' }]}
        >
          <DatePicker style={{ width: '100%' }} />
        </Form.Item>
        <Form.Item
          name="image"
          label="物资照片"
        >
          <Upload
            listType="picture-card"
            maxCount={1}
            beforeUpload={() => false}
            onChange={({ fileList }) => setFileList(fileList)}
          >
            <div>
              <PlusOutlined />
              <div style={{ marginTop: 8 }}>上传照片</div>
            </div>
          </Upload>
        </Form.Item>
      </Form>
    </Modal>
  );

  // 批量导入模态框
  const renderImportModal = () => (
    <Modal
      title="批量导入物资"
      visible={importModalVisible}
      onCancel={() => setImportModalVisible(false)}
      onOk={() => {
        message.success('导入成功');
        setImportModalVisible(false);
      }}
    >
      <Space direction="vertical" style={{ width: '100%' }}>
        <Button 
          icon={<FileExcelOutlined />}
          onClick={handleDownloadTemplate}
        >
          下载导入模板
        </Button>
        <Upload.Dragger
          accept=".xlsx,.xls"
          beforeUpload={() => false}
          onChange={({ fileList }) => console.log(fileList)}
        >
          <p className="ant-upload-drag-icon">
            <ImportOutlined />
          </p>
          <p className="ant-upload-text">点击或拖拽文件到此区域上传</p>
          <p className="ant-upload-hint">
            支持 .xlsx, .xls 格式的文件
          </p>
        </Upload.Dragger>
      </Space>
    </Modal>
  );

  // 图片预览模态框
  const renderImageModal = () => (
    <Modal
      visible={imageModalVisible}
      footer={null}
      onCancel={() => setImageModalVisible(false)}
    >
      <img alt="物资照片" style={{ width: '100%' }} src={currentImage} />
    </Modal>
  );

  return (
    <div className='container'>
      {renderStatistics()}
      {renderSearchBar()}
      
      <Table
        columns={mainColumns}
        dataSource={mainData}
        expandable={{
          expandedRowKeys,
          onExpandedRowsChange: (keys) => setExpandedRowKeys(keys as string[]),
          expandIcon: ({ expanded, onExpand, record }) => (
            <CaretRightOutlined
              rotate={expanded ? 90 : 0}
              onClick={e => onExpand(record, e)}
              style={{ cursor: 'pointer', color: '#666' }}
            />
          ),
          expandedRowRender: (record) => (
            <div className='expandedContent'>
              <div className='expandedHeader'>
                <h4>物资详情 - {record.itemName}</h4>
                <Space>
                  <Button icon={<PrinterOutlined />}>打印</Button>
                  <Button type="primary" icon={<PlusOutlined />}>
                    新增入库
                  </Button>
                </Space>
              </div>
              <Table
                columns={detailColumns}
                dataSource={detailData}
                pagination={false}
                className='detailTable'
              />
            </div>
          ),
        }}
        rowSelection={{
          onChange: (_, selectedRows) => setSelectedRows(selectedRows),
          selectedRowKeys: selectedRows.map(item => item.key),
        }}
        loading={loading}
        pagination={{
          total: 50,
          pageSize: 10,
          showQuickJumper: true,
          showSizeChanger: true,
          showTotal: (total) => `共 ${total} 条`,
        }}
        className='mainTable'
      />

      {renderAddModal()}
      {renderImportModal()}
      {renderImageModal()}
    </div>
  );
};

export default EmergencyStock;
